// 获取DOM元素
const amountEl = document.getElementById('amount');
const fromCurrencyEl = document.getElementById('from-currency');
const toCurrencyEl = document.getElementById('to-currency');
const resultEl = document.getElementById('result');
const convertBtn = document.getElementById('convert-btn');
const swapBtn = document.getElementById('swap-btn');
const exchangeRateEl = document.getElementById('exchange-rate');
const lastUpdatedEl = document.getElementById('last-updated');

// 汇率API地址 - 使用免费开放API
const API_URL = 'https://open.er-api.com/v6/latest/';

// 货币列表
const currencies = {
    'CNY': '人民币 (CNY)',
    'USD': '美元 (USD)',
    'EUR': '欧元 (EUR)',
    'GBP': '英镑 (GBP)',
    'JPY': '日元 (JPY)',
    'KRW': '韩元 (KRW)',
    'AUD': '澳元 (AUD)',
    'CAD': '加元 (CAD)',
    'HKD': '港币 (HKD)',
    'SGD': '新加坡元 (SGD)',
    'THB': '泰铢 (THB)',
    'CHF': '瑞士法郎 (CHF)',
    'RUB': '俄罗斯卢布 (RUB)',
    'INR': '印度卢比 (INR)',
    'BRL': '巴西雷亚尔 (BRL)'
};

// 初始化
async function initialize() {
    // 填充货币选择列表
    populateCurrencyLists();
    
    // 默认选择
    fromCurrencyEl.value = 'USD';
    toCurrencyEl.value = 'CNY';
    
    // 获取初始汇率数据
    await fetchExchangeRate();
    
    // 绑定事件
    convertBtn.addEventListener('click', convertCurrency);
    swapBtn.addEventListener('click', swapCurrencies);
    fromCurrencyEl.addEventListener('change', updateRateInfo);
    toCurrencyEl.addEventListener('change', updateRateInfo);
    amountEl.addEventListener('input', debounce(convertCurrency, 500));
}

// 填充货币选择列表
function populateCurrencyLists() {
    Object.entries(currencies).forEach(([code, name]) => {
        const fromOption = document.createElement('option');
        fromOption.value = code;
        fromOption.textContent = name;
        fromCurrencyEl.appendChild(fromOption);
        
        const toOption = document.createElement('option');
        toOption.value = code;
        toOption.textContent = name;
        toCurrencyEl.appendChild(toOption);
    });
}

// 获取汇率数据
async function fetchExchangeRate() {
    try {
        const fromCurrency = fromCurrencyEl.value;
        // 确保URL构建正确
        const url = `${API_URL}${fromCurrency}`;
        console.log("API请求URL:", url); // 调试日志
        
        const response = await fetch(url);
        
        if (!response.ok) {
            throw new Error(`无法获取汇率数据 (${response.status}: ${response.statusText})`);
        }
        
        const data = await response.json();
        console.log("API返回数据:", data); // 调试日志
        
        // 检查数据格式是否正确
        if (!data || !data.rates) {
            throw new Error('API返回数据格式错误: 没有汇率信息');
        }
        
        // 更新最后更新时间
        if (data.time_last_update_unix) {
            const date = new Date(data.time_last_update_unix * 1000);
            lastUpdatedEl.textContent = `最后更新时间: ${date.toLocaleString()}`;
        } else {
            lastUpdatedEl.textContent = `最后更新时间: ${new Date().toLocaleString()}`;
        }
        
        // 更新汇率信息
        updateRateInfoWithRates(data.rates);
        
        // 执行转换
        convertCurrencyWithRates(data.rates);
        
        return data.rates;
    } catch (error) {
        console.error('获取汇率失败:', error);
        alert('获取汇率数据失败: ' + error.message + '\n请检查网络连接或尝试使用代理。');
        // 初始化一些默认值以防止页面出错
        exchangeRateEl.textContent = '无法获取最新汇率';
        lastUpdatedEl.textContent = '数据获取失败';
    }
}

// 转换货币
function convertCurrency() {
    fetchExchangeRate().then(rates => {
        if (rates) {
            convertCurrencyWithRates(rates);
        }
    });
}

// 使用已获取的汇率转换货币
function convertCurrencyWithRates(rates) {
    if (!rates) return;
    
    const amount = parseFloat(amountEl.value);
    
    if (isNaN(amount) || amount <= 0) {
        resultEl.value = '';
        return;
    }
    
    const toCurrency = toCurrencyEl.value;
    if (!rates[toCurrency]) {
        console.error(`找不到汇率: ${toCurrency}`);
        resultEl.value = '无数据';
        return;
    }
    
    const rate = rates[toCurrency];
    const result = amount * rate;
    
    // 根据货币类型决定小数位数
    const precision = needsHighPrecision(toCurrency) ? 4 : 2;
    resultEl.value = result.toFixed(precision);
}

// 判断是否需要高精度（如日元等）
function needsHighPrecision(currency) {
    return ['JPY', 'KRW', 'INR', 'RUB'].includes(currency) ? false : true;
}

// 交换货币
function swapCurrencies() {
    const temp = fromCurrencyEl.value;
    fromCurrencyEl.value = toCurrencyEl.value;
    toCurrencyEl.value = temp;
    
    fetchExchangeRate();
}

// 更新汇率信息
function updateRateInfo() {
    fetchExchangeRate().then(rates => {
        if (rates) {
            updateRateInfoWithRates(rates);
        }
    });
}

// 使用已获取的汇率更新汇率信息
function updateRateInfoWithRates(rates) {
    if (!rates) return;
    
    const fromCurrency = fromCurrencyEl.value;
    const toCurrency = toCurrencyEl.value;
    
    if (!rates[toCurrency]) {
        console.error(`找不到汇率: ${toCurrency}`);
        exchangeRateEl.textContent = `无法获取 ${fromCurrency} 到 ${toCurrency} 的汇率`;
        return;
    }
    
    const rate = rates[toCurrency];
    const precision = needsHighPrecision(toCurrency) ? 4 : 2;
    exchangeRateEl.textContent = `1 ${fromCurrency} = ${rate.toFixed(precision)} ${toCurrency}`;
}

// 防抖函数
function debounce(func, delay) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), delay);
    };
}

// 初始化应用
document.addEventListener('DOMContentLoaded', initialize); 